/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.vsu.cs.kis.elections.client;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirill
 */
public class ClientController {

	private static ClientController inner;
	
	public static boolean isActive = false;

	public List<ClientThread> socketThreads;
	
	//public List<ClientTaskRPC> rpcTasks;
	
	public static int delay = 1000; 

	private ClientController() {
		/** init Socket and bind RPC */
		//rpcTasks = new ArrayList<ClientTaskRPC>();
		socketThreads = new ArrayList<ClientThread>();
	}
	
	public static ClientController initClient() {
		if (inner == null) {
			inner = new ClientController();
			isActive = true;
			return inner;
		}
		return inner;
	}
	
	public static void stopServer() {
		isActive = false;
	}

	public void addSoscketClients(int count) {
		for (int i = 0; i < count; i++) {
			ClientThread cl=new ClientThread();
			socketThreads.add(cl);
			Thread thr=new Thread(cl);
			thr.start();
		}
	}
	
/*	public void addRPCclients(int count) {
		for (int i = 0; i < count; i++) {
			rpcTasks.add(new ClientTaskRPC(socket));
		}
	}*/

	public void removeSocketClients(int count) {
		Integer result = null; 
		if (socketThreads.size() >= count){
			result = 0;
			for (int i = 0; i < count; i++) {
				socketThreads.get(0).stop();
				socketThreads.remove(0);
				result++;
			}
		}
		ElectionMain.printResult(" ",  " ", result);
	}

	/*public void removeRPCclients(int count) {
		Integer result = null; 
		if (rpcTasks.size() >= count){
			result = 0;
			for (int i = 0; i < count; i++) {
				rpcTasks.get(0).stop();
				rpcTasks.remove(0);
				result++;
			}
		}
		ElectionMain.printResult(" ",  " ", result);
	}
*/
	public void setPing(int delay) {
		ClientController.delay = delay;
	}

	/*public void setRPCclients(int count) {
		if (rpcTasks.size() > count){
			removeRPCclients(count - rpcTasks.size());
		} else if (rpcTasks.size() < count){
			addRPCclients(rpcTasks.size() - count);
		} else {
			ElectionMain.printResult(" ",  " ", 0);
		}
	}
*/
	public void setSocketclients(int count) {
		if (socketThreads.size() > count){
			removeSocketClients(count - socketThreads.size());
		} else if (socketThreads.size() < count){
			addSoscketClients(socketThreads.size() - count);
		} else {
			ElectionMain.printResult(" ",  " ", 0);
		}
	}

	public void getStatistics() {
		// TODO Auto-generated method stub
	}
}
